let htmlTemplete = `
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <title>[#DocTitle#]文档说明</title>
    <style>
        .top-title {
            position: absolute;
            top: 0px;
            left: 0px;
            width: 100%;
            height: 40px;
            box-shadow: 1px 2px #008cff;
        }

        .title {
            color: #008cff;
            font-size: 25px;
            font-weight: 500;
            line-height: 40px;
            display: inline-block;
            float: left;
            padding-left: 10px;
        }

        .date-time {
            color: #6b6b6b;
            font-size: 16px;
            line-height: 40px;
            display: inline-block;
            float: right;
            padding-right: 10px;
        }

        .file-path {
            position: absolute;
            top: 40px;
            left: 0px;
            display: block;
            border-left: 5px solid #008cff;
            height: 30px;
            width: calc(100% - 10px);
            line-height: 30px;
            color:#FFFFFF;
            font-size: 18px;
            padding-left: 5px;
            background-color: #008cff;
        }

        .left-tree {
            position: absolute;
            padding: 10px;
            top: 72px;
            left: 0px;
            width: calc(65% - 20px);
            height: calc(100% - 92px);
            overflow: auto;
            background-color: #efefef;
			z-index: 100;
        }

        .right-content {
            position: absolute;
            padding: 10px;
            top: 72px;
            right: 0px;
            width: calc(35% - 20px);
            height: calc(100% - 92px);
            overflow: auto;
			background-color: #FFFFFF;
			z-index: 200;
			transition: all .4s ease-in-out;
        }

        .js {
            background: url() no-repeat center;
            background-size: auto;
        }

        .json {
            background: url() no-repeat center;
        }

        .vue {
            background: url() no-repeat center;
        }

        .dir {
            background: url() no-repeat center;
        }

        .other {
            background: url() no-repeat center;
        }

        .tree-item {
            display: block;
            height: 20px;
            width: 100%;
			overflow:hidden;
			transition: all .4s ease-in-out;
        }

        [#CSS#]

        .tree-item-icon {
            position: relative;
            display: inline-block;
            height: 20px;
            width: 20px;
            background-size: 90% 90%;
            float: left;
        }

        .tree-item-path {
            display: inline-block;
            font-size:13px;
            height: 20px;
            text-align: left;
            line-height: 20px;
            float: left;
        }

		.tree-item-title {
			display: inline-block;
			height: 20px;
			width: 160px;
			overflow: hidden;
            font-size:12px;
			text-overflow: ellipsis;
			white-space: nowrap;
			text-align: right;
			line-height: 20px;
			float: right;
		}

        .author {
            float: right;
            font-size: 12px;
        }

        .tree-item:hover {
            cursor: pointer;
            background-color: #eefaff;
            color: #008cff
        }

        .file-title {
            display: block;
            border-left: 2px solid #008cff;
            height: 25px;
            font-size: 16px;
            color: #4a4a4a;
            padding-left: 5px;
            margin-top: 0px;
            border-bottom: 1px solid #dcdcdc;
            overflow: hidden; 
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        .file-title span{
            height: 25px;
            display: inline-block;
            width:calc(100% - 200px);
            overflow: hidden; 
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        .author {
            float: right;
            font-size: 12px;
            display: inline-block;
            height: 25px;
            line-height:25px;

        }
        .file-content {
            display: block;
            font-size: 14px;
            padding: 20px 0px;
        }

        .detail {
            display: none;
        }

        .detail span {
            display: none;
        }
		.full-remark{
			width: 30px;
			height: 30px;
			position: absolute;
			right: 20px;
			bottom: 20px;
			z-index: 1000;
			background-color: #008cff;
			font-size: 12px;
			line-height: 30px;
			text-align: center;
			color: #FFFFFF;
			border-radius: 5px;
			cursor: pointer;
		}
    </style>
</head>

<body id="page">
    <div>
		<div id="fullremark" class="full-remark">展开</div>
        <div class="top-title">
            <div class="title">[#DocTitle#]文档说明</div>
            <div class="date-time">[文件夹注释：[#DirRemarkNum#]/[#DirNum#]、 文件注释：[#FileRemarkNum#]/[#FileNum#]]，更新于：[#DateTime#]</div>
        </div>
        <div id="filepath" class="file-path">文件路径</div>
        <div class="left-tree">
		 [#FileTree#]
        </div>
        <div id="rightcontent" class="right-content">
            <div class="file-title"><span id="filetitle"></span><i id="author" class="author"></i></div>
            <div id="filecontent" class="file-content">/*<br>[{@开发者@}]<br><br>[{#文件或目录的简要说明#}]<br><br>[{*详细说明在这里描述*}]<br>*/<br><br>注释方式用//、/*、<!---->、/**等都可以，不同语言使用不同注释。<br>以上就是在文件中的注释格式.<br>如果要对文件夹注释，在文件夹下创建README.md，按照以上格式插入即可</div>
        </div>
        <div class="detail">
			[#FileDetailRemark#]
        </div>
    </div>
</body>
<script>
    let allfile=[#IdIndex#]
    function bindEvent(i) {
        document.getElementById("doc" + i).addEventListener('click', function () {
            document.getElementById("filepath").innerText = "[#DocTitle#]/"+document.getElementById("path" + i).innerText;
            document.getElementById("filetitle").innerText = document.getElementById("title" + i).innerText.trim()!=''?document.getElementById("title" + i).innerText:'未注释';
            document.getElementById("filecontent").innerText =document.getElementById("detail" + i).innerText.trim()!=''?document.getElementById("detail" + i).innerText:'未注释';
            document.getElementById("author").innerText =document.getElementById("author" + i).innerText;
            let current_level=Number(document.getElementById("doc" + i).getAttribute("deepLevel"))
            if(document.getElementById("doc" + i).getAttribute("dir")=='true')
			{
				let file_index=i+1
				if(file_index==allfile){
					return
				}
				let hidden_state=document.getElementById("doc" + file_index).style.height == "20px" ? "0px":"20px"
				while(file_index <= allfile)
				{
					if(Number(document.getElementById("doc" + file_index).getAttribute("deepLevel")) > current_level){
						document.getElementById("doc" + i).style.backgroundColor=hidden_state == "0px"?"#abd9ff":"rgba(0,0,0,0)"
						document.getElementById("doc" + file_index).style.height = hidden_state
						file_index+=1
					}else{
						return
					}
				}
			}
        })
    }
    window.onload = function () {
        for (var i = 1; i <= [#IdIndex#]; i++) {
            bindEvent(i);
        }
        document.getElementById("fullremark").addEventListener('click', function () {
			let pageWidth=document.getElementById("page").offsetWidth
			let remarkWidth=document.getElementById("rightcontent").offsetWidth
			if(Number(remarkWidth)/Number(pageWidth) < 0.5){
				document.getElementById("rightcontent").style.width=pageWidth+"px"
				document.getElementById("fullremark").innerText ="还原"
			}else{
				document.getElementById("rightcontent").style.width=(pageWidth*0.4)+"px"
				document.getElementById("fullremark").innerText ="展开"
			}
		})
    }
</script>

</html>
`
const fs = require('fs');
/**忽略的文件夹 */
const ignore_dir = ['node_modules', 'demo','target']
/**忽略的文件 */
const ignore_file = ['README.md', 'README.en.md', 'scanfile.js', 'LICENSE']
/**忽略的文件，后缀匹配 */
const ignore_suffix = ['.png', '.jpg', '.svg', '.jpeg', '.ttf', '.ttf3', '.woff', '.woff2', '.eot','.iml','.log']
const dir = __dirname
fs.writeFileSync(dir + "/docFile.html", "")
/**是否初始化README.md文件 */
const initReadMeFile = false
const projectName = dir.substring(dir.lastIndexOf('/') + 1)
let dirContent = ""
let RemarkContent = ""
let IdIndex = 0
let FileNum = 0
let DirNum = 0
let FileRemarkNum = 0
let DirRemarkNum = 0

function dirDeepCss(num){
    let deepcss=''
    for(let i=0;i<=num;i++){
        deepcss+=`        
        .tree-level${i} {
            position: relative;
            display: inline-block;
            height: 20px;
            width: 0px;
            top: 5px;
            padding-left: ${i*20}px;
            background-size: 90% 90%;
            float: left;
        }`
    }
    return deepcss
}

function curentDateTime() {
    var date = new Date();
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var mytime = date.toLocaleTimeString();
    var time = year + "-" + month + "-" + day + ' ' + mytime;
    return time;
}

function getTreeItem(index, deppIndex, filetype, filename, filedoc, author) {
    let temp = `
		<div class="tree-item" id="doc${index}" deepLevel="${deppIndex}" dir="${filetype=='dir'}">
			<div class="tree-level${deppIndex}"></div>
			<div class="tree-item-icon ${filetype}"></div>
			<div class="tree-item-path" id="file${index}">${filename}</div>
			<div class="tree-item-title" id="title${index}">${filedoc}</div>
			<div class="detail" id="author${index}">${author}</div>
		</div>
	`
    return temp
}

function getDetailItem(index, docdetail, path) {
    let temp = `
		<span id="detail${index}">${docdetail}</span>
		<span id="path${index}">${path.substring(dir.length+1)}</span>
	`
    return temp
}

function writeFile(deppIndex, path) {
    try {
        if (ignore_suffix.filter(item => path.endsWith(item)).length > 0) return;
        if (!ignore_file.includes(path.substring(path.lastIndexOf('/') + 1))) {
            FileNum = FileNum + 1
            let fileStr = fs.readFileSync(path, 'utf-8').replace(/[\n\r]/g, 'hhjkg').replace(/[\n]/g, 'jjshh')
            let txtFileDoc = fileStr.match(/\[{#(.+?)\#}\]/gi)
            let txtRemark = fileStr.match(/\[{\*(.+?)\*}\]/gi)
            let txtAuthor = fileStr.match(/\[{@(.+?)@}\]/gi)

            let temp_filedoc = txtFileDoc != null ? txtFileDoc[0].substring(3, txtFileDoc[0].length - 3) : ''
            if (temp_filedoc != '') {
                FileRemarkNum = FileRemarkNum + 1
            }
            let temp_fileremark = txtRemark != null ? txtRemark[0].substring(3, txtRemark[0].length - 3) : ''
            let temp_filetype = 'other'
            if (path.endsWith('.js')) {
                temp_filetype = 'js'
            } else if (path.endsWith('.vue')) {
                temp_filetype = 'vue'
            } else if (path.endsWith('.json')) {
                temp_filetype = 'json'
            }

            let temp_author = ''
            if (txtAuthor != null) {
                temp_author = txtAuthor[0].substring(3, txtAuthor[0].length - 3)
            }

            IdIndex = IdIndex + 1
            dirContent = dirContent + getTreeItem(IdIndex, deppIndex, temp_filetype, path.substring(path.lastIndexOf('/') + 1), temp_filedoc, temp_author)
            RemarkContent = RemarkContent + getDetailItem(IdIndex, temp_fileremark, path)
        }

    } catch (err) {
        console.log("err=" + err);
    }
}

function scanDir(deppIndex, dirName) {
    try {
        const files = fs.readdirSync(dirName);
        let temp_filename = dirName.substring(dirName.lastIndexOf('/') + 1)
        let temp_dirdoc = ''
        let temp_dirremark = ''
        let temp_author = ''
        try {
            let readme = fs.readFileSync(dirName + '/README.md', 'utf-8')
            readme=readme.replace(/\r?\n/g, "<br>");
            if (readme != null) {
                let txtDirDoc = readme.match(/\[{#(.+?)\#}\]/gi)
                let txtDirRemark = readme.match(/\[{\*(.+?)\*}\]/gi)
                let txtAuthor = readme.match(/\[{@(.+?)@}\]/gi)
                console.log("readme="+readme)
                console.log("txtDirDoc="+txtDirDoc)
                console.log("txtDirRemark="+txtDirRemark)
                console.log("txtAuthor="+txtAuthor)

                if (txtDirDoc != null) {
                    temp_dirdoc = txtDirDoc[0].substring(3, txtDirDoc[0].length - 3)
                    DirRemarkNum = DirRemarkNum + 1
                }
                if (txtDirRemark != null && dirName.substring(dir.length) != '') {
                    temp_dirremark = txtDirRemark[0].substring(3, txtDirRemark[0].length - 3)
                }
                if (txtAuthor != null) {
                    temp_author = txtAuthor[0].substring(3, txtAuthor[0].length - 3)
                }

            }
        } catch (err) {
            if (initReadMeFile) {
                fs.writeFileSync(dirName + '/README.md', "[{@开发者@}]<br>[{#目录说明#}]<br>[{*详细说明描述*}]");
            }
        }
        IdIndex = IdIndex + 1
        DirNum = DirNum + 1
        dirContent = dirContent + getTreeItem(IdIndex, deppIndex, 'dir', temp_filename, temp_dirdoc, temp_author)
        RemarkContent = RemarkContent + getDetailItem(IdIndex, temp_dirremark, dirName)
        files.forEach(file => {
            if (!file.startsWith(".") && !ignore_dir.includes(file)) {
                scanDir(deppIndex + 1, dirName + "/" + file)
            }
        });
    } catch (err) {
        writeFile(deppIndex, err.path)
    }
}

scanDir(0, dir)


htmlTemplete = htmlTemplete.replace("[#CSS#]", dirDeepCss(16))
htmlTemplete = htmlTemplete.replace(/\[#DocTitle\#\]/g, projectName)
htmlTemplete = htmlTemplete.replace(/\[#DateTime\#\]/g, curentDateTime)
htmlTemplete = htmlTemplete.replace("[#FileTree#]", dirContent)
htmlTemplete = htmlTemplete.replace("[#FileDetailRemark#]", RemarkContent)
htmlTemplete = htmlTemplete.replace(/\[#IdIndex\#\]/g, IdIndex)

htmlTemplete = htmlTemplete.replace("[#FileNum#]", FileNum)
htmlTemplete = htmlTemplete.replace("[#DirNum#]", DirNum)
htmlTemplete = htmlTemplete.replace("[#FileRemarkNum#]", FileRemarkNum)
htmlTemplete = htmlTemplete.replace("[#DirRemarkNum#]", DirRemarkNum)

htmlTemplete = htmlTemplete.replace(new RegExp('hhjkg', "g"), '\n\r').replace(new RegExp('jjshh', "g"), '\n')

fs.appendFileSync(dir + "/docFile.html", htmlTemplete)
module.exports = {}